<template>
	<el-date-picker
		v-model="date"
		size="mini"
		type="daterange"
		range-separator="至"
		start-placeholder="开始日期"
		end-placeholder="结束日期"
		value-format="yyyy-MM-dd"
		:picker-options="pickerOptions"
		@change="datePickerChange"
	></el-date-picker>
</template>

<script>
import moment from 'moment';

export default {
	data() {
		let start = moment()
			.hour(0)
			.minute(0)
			.second(0)
			.format('YYYY-MM-DD 00:00:00');

		let end = moment().format('YYYY-MM-DD HH:mm:ss');

		return {
			date: [start, end],
			pickerOptions: {
				shortcuts: [
					{
						text: '今天',
						onClick(picker) {
							let start = moment()
								.hour(0)
								.minute(0)
								.second(0)
								.format('YYYY-MM-DD HH:mm:ss');

							let end = moment().format('YYYY-MM-DD HH:mm:ss');

							picker.$emit('pick', [start, end]);
						}
					},
					{
						text: '昨天',
						onClick(picker) {
							let d = moment().subtract(1, 'day');

							let start = d
								.hour(0)
								.minute(0)
								.second(0)
								.format('YYYY-MM-DD HH:mm:ss');
							let end = d
								.hour(23)
								.minute(59)
								.second(59)
								.format('YYYY-MM-DD HH:mm:ss');

							picker.$emit('pick', [start, end]);
						}
					},
					{
						text: '近七天',
						onClick(picker) {
							let start = moment()
								.subtract(6, 'day')
								.hour(0)
								.minute(0)
								.second(0)
								.format('YYYY-MM-DD HH:mm:ss');

							let end = moment()
								.hour(23)
								.minute(59)
								.second(59)
								.format('YYYY-MM-DD HH:mm:ss');

							picker.$emit('pick', [start, end]);
						}
					},
					{
						text: '近30天',
						onClick(picker) {
							let start = moment()
								.subtract(29, 'day')
								.hour(0)
								.minute(0)
								.second(0)
								.format('YYYY-MM-DD HH:mm:ss');

							let end = moment()
								.hour(23)
								.minute(59)
								.second(59)
								.format('YYYY-MM-DD HH:mm:ss');

							picker.$emit('pick', [start, end]);
						}
					}
				]
			}
		};
	},
	methods: {
		datePickerChange(val) {
			if (val) {
				let [start, end] = val;
				start = moment(start)
					.hour(0)
					.minute(0)
					.second(0)
					.format('YYYY-MM-DD HH:mm:ss');

				end = moment(end)
					.hour(23)
					.minute(59)
					.second(59)
					.format('YYYY-MM-DD HH:mm:ss');

				this.$emit('change', [start, end]);
			} else {
				this.$emit('refresh');
			}
		}
	}
};
</script>
<style lang="scss" scoped>
::v-deep.el-range-editor--mini.el-input__inner {
	width: 292px;
}
</style>
